package com.bhs.sansonglogistics.ui.enterprise;

import static android.view.Gravity.CENTER;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.CompanyCollect;
import com.bhs.sansonglogistics.bean.CompanyInfoBean;
import com.bhs.sansonglogistics.bean.CouponList;
import com.bhs.sansonglogistics.bean.OperationEvent;
import com.bhs.sansonglogistics.bean.SlideshowBean;
import com.bhs.sansonglogistics.bean.VideoDataBean;
import com.bhs.sansonglogistics.bean.event.CompanyInfo;
import com.bhs.sansonglogistics.bean.event.ViewPageStatus;
import com.bhs.sansonglogistics.dialog.BottomSelectPhone2Dialog;
import com.bhs.sansonglogistics.dialog.MoreVideoDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.DiscountCouponAdapter;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MapUtil;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.MyBasePopupView;
import com.bhs.sansonglogistics.view.Watermark;
import com.bhs.sansonglogistics.view.banner.AutoScrollViewPager;
import com.bhs.sansonglogistics.view.banner.BannerIndicator;
import com.bhs.sansonglogistics.view.banner.ViewPagerAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.lxj.xpopup.util.SmartGlideImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 公司资料
 */
public class CompanyProfileFragment extends BaseFragment implements NetCallBack, View.OnClickListener {
    private LinearLayout mLlScore;
    private CompanyInfo companyInfo;
    private RelativeLayout mRlCarousel;
    private AutoScrollViewPager mVpCarousel;
    private BannerIndicator mIndicator;
    private TextView mTvCompanyName;
    private ImageView mIvAuthority;
    private TextView mTvVat;
    private TextView mTvPageView;
    private TextView mTvOrderQuantity;
    private TextView mTvQuantityCollection;
    private TextView mTvAnnouncement;
    private TextView mTvPrincipal;
    private LinearLayout mLlPhone;
    private TextView mTvPhone;
    private LinearLayout mLlLandlineNumber;
    private EditText mTvLandlineNumber;
    private TextView mTvCompanyAddress;
    private FrameLayout mFlLocation;
    private TextView mTvSuoshuyuanqu;
    private TextView mTvBusinessLicense;
    private TextView mTvTransportPolicy;
    private TextView mTvQualitySpecialLine;
    private TextView mTvRangeTransport;
    private CompanyInfoBean infoBean;
    private TextView mTvIndexes;
    private List<SlideshowBean> bannerList = new ArrayList<>();
    private RecyclerView mRvList;
    private DiscountCouponAdapter mAdapter;
    private int logistics_id;
    private int myLogistics_id;

    public static CompanyProfileFragment newInstance(int logistics_id) {
        CompanyProfileFragment companyProfileFragment = new CompanyProfileFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("logistics_id", logistics_id);
        companyProfileFragment.setArguments(bundle);
        return companyProfileFragment;
    }


    @Override
    public int initLayout() {
        return R.layout.fragment_company_profile;
    }

    @Override
    public void initView(View root) {
        //注册监听
        EventBus.getDefault().register(this);
        logistics_id = getArguments().getInt("logistics_id");
        myLogistics_id = SharedPreferencesUtils.getInt(getContext(), "logistics_id", 0);
        mLlScore = root.findViewById(R.id.ll_score);
        mRlCarousel = root.findViewById(R.id.rl_carousel);
        mVpCarousel = root.findViewById(R.id.vp_carousel);
        mIndicator = root.findViewById(R.id.indicator);
        mTvCompanyName = root.findViewById(R.id.tv_company_name);
        mIvAuthority = root.findViewById(R.id.iv_authority);
        mTvVat = root.findViewById(R.id.tv_vat);
        mTvPageView = root.findViewById(R.id.tv_page_view);
        mTvOrderQuantity = root.findViewById(R.id.tv_order_quantity);
        mTvQuantityCollection = root.findViewById(R.id.tv_quantity_collection);
        mTvAnnouncement = root.findViewById(R.id.tv_announcement);
        mTvPrincipal = root.findViewById(R.id.tv_principal);
        mLlPhone = root.findViewById(R.id.ll_phone);
        mTvPhone = root.findViewById(R.id.tv_phone);
        mTvPhone.setOnClickListener(this);
        root.findViewById(R.id.iv_phone).setOnClickListener(this);
        mLlLandlineNumber = root.findViewById(R.id.ll_landline_number);
        mTvLandlineNumber = root.findViewById(R.id.tv_landline_number);
        mTvLandlineNumber.setOnClickListener(this);
        root.findViewById(R.id.iv_landline_number).setOnClickListener(this);
        mTvCompanyAddress = root.findViewById(R.id.tv_company_address);
        mFlLocation = root.findViewById(R.id.fl_location);
        mTvSuoshuyuanqu = root.findViewById(R.id.tv_suoshuyuanqu);
        mTvBusinessLicense = root.findViewById(R.id.tv_business_license);
        mTvTransportPolicy = root.findViewById(R.id.tv_transport_policy);
        mTvQualitySpecialLine = root.findViewById(R.id.tv_quality_special_line);
        mTvRangeTransport = root.findViewById(R.id.tv_range_transport);
        mTvBusinessLicense.setOnClickListener(this);
        mTvTransportPolicy.setOnClickListener(this);
        mTvQualitySpecialLine.setOnClickListener(this);
        mTvRangeTransport.setOnClickListener(this);
        mTvIndexes = root.findViewById(R.id.tv_indexes);
        mRvList = root.findViewById(R.id.rv_list);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mVpCarousel != null) {
            mVpCarousel.stopAutoPlay();
        }
    }

    private void score(String scores, String commentNum) {
        double score = Double.parseDouble(scores) / (Integer.parseInt(commentNum) + 1);
        int num = (int) score;
        double residue = score - num;
        for (int i = 0; i < num; i++) {
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(R.mipmap.ic_love);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(10, 0, 0, 0);
            lp.gravity = CENTER;
            imageView.setLayoutParams(lp);
            mLlScore.addView(imageView);
        }

        if (num != 5) {
            for (int i = 0; i < 5 - num; i++) {
                ImageView imageView = new ImageView(getContext());
                if (i == 0) {
                    if (residue >= 0.5) {
                        imageView.setImageResource(R.mipmap.ic_love_half);
                    } else {
                        imageView.setImageResource(R.mipmap.ic_empty_love);
                    }
                } else {

                    imageView.setImageResource(R.mipmap.ic_empty_love);
                }
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(10, 0, 0, 0);
                lp.gravity = CENTER;
                imageView.setLayoutParams(lp);
                mLlScore.addView(imageView);
            }
        }

        TextView textView = new TextView(getContext());
        textView.setText(String.format("%s分", MyUtils.format2(score)));
        textView.setTextColor(Color.parseColor("#FFFF6067"));
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 6;
        textView.setLayoutParams(lp);
        textView.setTextSize(12);
        mLlScore.addView(textView);
    }

    @Override
    public void initData() {
        loadingPopupShow();
        if (logistics_id > 0) {
            networkRequest(netApi.get_company_infother(logistics_id), this);
        } else {
            networkRequest(netApi.getCompanyInfo(), this);
        }
        networkRequest(netApi.couponList(1, 10, 1, logistics_id), this, 666);
        mAdapter = new DiscountCouponAdapter();
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.HORIZONTAL, false));

    }


    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            loadingPopupDismiss();
            infoBean = new Gson().fromJson(json, CompanyInfoBean.class);
            if (infoBean.isStatus()) {
                companyInfo = infoBean.getData().getCompany_info();
                EventBus.getDefault().postSticky(companyInfo);
                EventBus.getDefault().post(new CompanyCollect(infoBean.getData().getCollect_status()));
                setData();
            } else {
                ToastUtil.show(infoBean.getMsg());
            }
        } else {
            CouponList couponList = new Gson().fromJson(json, CouponList.class);
            if (couponList.isStatus()) {
                mAdapter.setNewData(couponList.getData().getList());
            }
        }
    }

    @Subscribe
    public void onEvent(OperationEvent event) {
        if (event.getType().equals("百度地图")) {
            openBaiDuMap();
        } else if (event.getType().equals("高德地图")) {
            openGaoDeMap();
        } else if (event.getType().equals("立即联系")) {
            contactImmediately();
        }
    }

    BottomSelectPhone2Dialog bottomSelectDialog;
    BasePopupView basePopupView;

    private void contactImmediately() {

        if (basePopupView == null) {
            bottomSelectDialog = new BottomSelectPhone2Dialog(getContext(),
                    companyInfo.getMobile(), companyInfo.getFixed_telephone(), "");
            basePopupView = new XPopup.Builder(getContext())
                    .asCustom(bottomSelectDialog)
                    .show();
            bottomSelectDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    networkRequest(netApi.company_calll_company(logistics_id), null);
                }
            });
        } else {
            basePopupView.show();
        }
    }

    private void openGaoDeMap() {
        if (MapUtil.isGdMapInstalled()) {
            MapUtil.openGaoDeNavi(getContext(), 0, 0, null,
                    Double.parseDouble(companyInfo.getLatitude()), Double.parseDouble(companyInfo.getLongitude()),
                    companyInfo.getAddress());
        } else {
            //这里必须要写逻辑，不然如果手机没安装该应用，程序会闪退，这里可以实现下载安装该地图应用
            ToastUtil.show("尚未安装高德地图");
        }
    }

    private void openBaiDuMap() {
        if (MapUtil.isBaiduMapInstalled()) {
            MapUtil.openBaiDuNavi(getContext(), 0, 0, null,
                    Double.parseDouble(companyInfo.getLatitude()), Double.parseDouble(companyInfo.getLongitude()),
                    companyInfo.getAddress());
        } else {
            //这里必须要写逻辑，不然如果手机没安装该应用，程序会闪退，这里可以实现下载安装该地图应用
            ToastUtil.show("尚未安装百度地图");
        }
    }

    int num = 0;

    private void setData() {
        bannerList.clear();
        List<Object> objectList = new ArrayList<>();
        num = 0;
        if (!MyUtils.isEmpty(infoBean.getData().getCompany_imgs().getCompany_viedeos())) {
            num++;
            bannerList.add(new SlideshowBean(infoBean.getData().getCompany_imgs().getCompany_viedeos().get(0).getCover(), 2));
        }

        for (String s : infoBean.getData().getCompany_imgs_all()) {
            bannerList.add(new SlideshowBean(s));
            objectList.add(s);
        }

        if (bannerList.size() > 0) {
            ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(bannerList, getContext(), true, false);
            mVpCarousel.setAdapter(pagerAdapter);
            mTvIndexes.setVisibility(View.VISIBLE);
            mTvIndexes.setText(String.format("%s/%s", 1, bannerList.size()));
            mVpCarousel.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    mTvIndexes.setText(String.format("%s/%s", position % bannerList.size() + 1, bannerList.size()));
                }
            });
            mVpCarousel.startAutoPlay();
            pagerAdapter.setIOnItemClick(new ViewPagerAdapter.IOnItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (num > position) {
                        moreVideo();
                    } else {
                        BasePopupView dialog = new XPopup.Builder(getContext())
                                .animationDuration(0)
                                .asImageViewer(view.findViewById(R.id.iv_picture), position - num, objectList, null, new SmartGlideImageLoader())
                                .isShowSaveButton(false)
                                .show();
                        Watermark.getInstance().show(getContext(), dialog);
                    }
                }
            });
        }
        score(companyInfo.getGrade_score(), companyInfo.getComment_num());
        mTvCompanyName.setText(companyInfo.getCompany_name());
        mTvAnnouncement.setText(companyInfo.getPublic_notice());
        mTvPrincipal.setText(companyInfo.getContact());
        mTvPhone.setText(companyInfo.getMobile());
        MyUtils.setText(mTvLandlineNumber, companyInfo.getFixed_telephone());
        mTvCompanyAddress.setText(companyInfo.getAddress());
        mTvSuoshuyuanqu.setText(companyInfo.getPark_name());
        Spanned PageView = Html.fromHtml("浏览量:<font color=\"#000000\">" + companyInfo.getVisitor_count() + "</font>");
        mTvPageView.setText(PageView);
        Spanned OrderQuantity = Html.fromHtml("下单量:<font color=\"#000000\">" + companyInfo.getOrder_count() + "</font>");
        mTvOrderQuantity.setText(OrderQuantity);
        Spanned QuantityCollection = Html.fromHtml("收藏量:<font color=\"#000000\">" + companyInfo.getCollect_count() + "</font>");
        mTvQuantityCollection.setText(QuantityCollection);
        if (companyInfo.getIs_company_approve() == 1) {
            mIvAuthority.setVisibility(View.VISIBLE);
        } else {
            mIvAuthority.setVisibility(View.GONE);
        }
//        if(companyInfo.getIs_fapiao()==1){
//            mTvVat.setVisibility(View.VISIBLE);
//        }else {
//            mTvVat.setVisibility(View.GONE);
//        }


    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_business_license:
                startActivity(new Intent(getActivity(), CheckAttachmentActivity.class)
                        .putExtra("title", "营业执照")
                        .putExtra("attachment", infoBean.getData().getCompany_imgs().getLicense_pic().get(0)));
                break;
            case R.id.tv_transport_policy:
                if (infoBean.getData().getCompany_imgs().getInsurance_pics().size() > 0) {
                    startActivity(new Intent(getActivity(), CheckAttachmentActivity.class)
                            .putExtra("attachment", infoBean.getData().getCompany_imgs().getInsurance_pics().get(0))
                            .putExtra("title", "运输保单"));
                } else {
                    ToastUtil.show("还没上传");
                }
                break;
            case R.id.tv_range_transport:
                startActivity(new Intent(getActivity(), RangeTransportActivity.class).putExtra("logistics_id", logistics_id));
                break;
            case R.id.tv_phone:
            case R.id.iv_phone:
                MyUtils.callPhone(getContext(), mTvPhone.getText().toString());
                if (myLogistics_id != logistics_id) {
                    networkRequest(netApi.company_calll_company(logistics_id), null);
                }
                break;
            case R.id.tv_landline_number:
            case R.id.iv_landline_number:
                MyUtils.callPhone(getContext(), mTvLandlineNumber.getText().toString());
                if (myLogistics_id != logistics_id) {
                    networkRequest(netApi.company_calll_company(logistics_id), null);
                }
                break;

        }
    }


    private MoreVideoDialog dialog;

    private void moreVideo() {
        dialog = new MoreVideoDialog(getContext(), infoBean.getData().getCompany_imgs().getCompany_viedeos());
        dialog.show();
    }


}